package leetcode_tag.树;


import leetcode.TreeNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

public class LeetCode94 {

    List<Integer> result = new ArrayList<>();

    //左 中 右
    public List<Integer> inorderTraversal1(TreeNode root) {
        helper(root);
        return result;
    }

    //递归
    private void helper(TreeNode node) {
        if (node != null) {
            helper(node.left);
            result.add(node.val);
            helper(node.right);
        }
    }

    // 非递归 左 中 右
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> ans = new ArrayList<>();
        //先进后出
        Stack<TreeNode> nodes = new Stack<>();
        TreeNode current = root;
        while (!nodes.isEmpty()||current != null) {
            while (current != null) {
                nodes.add(current);
                current = current.left;
            }
            current = nodes.pop();
            ans.add(current.val);
            current = current.right;
        }
        return ans;
    }

}
